﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;
using System.Media;
using System.Reflection;

namespace FX.CC.Andon.EqKanban
{
    public partial class frmAndon : DevExpress.XtraEditors.XtraForm
    {
        IList<AndonDispWrapper> dispList = new List<AndonDispWrapper>();
        IDictionary<string, AndonDispWrapper> dispDc = new Dictionary<string, AndonDispWrapper>();
        object syncObj = new object();

        const int page_size = 5;
        SoundPlayer player;

        int clickCount = 0;
        int restartClickCount = 0;

        Thread dispTh;
        Action<IList<AndonDispWrapper>> actSetGridDataSource;

        public frmAndon()
        {
            InitializeComponent();
            this.gridControl2.Dock = DockStyle.Fill;
            this.Location = new Point(0, 0);


            actSetGridDataSource = new Action<IList<AndonDispWrapper>>(p =>
            {
                gridControl2.DataSource = p;
                gridView2.BestFitColumns();
                lbTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分");
            });


            dispTh = new Thread(DoGetData);
            dispTh.IsBackground = true;
            dispTh.Start();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            lbTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分");
            lbVersion.Text = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            player = new SoundPlayer(Application.StartupPath + "\\Alarm.wav");
            player.Load();
        }

        public void ReportError(AndonDispWrapper obj){
            lock (syncObj)
            {
                if (dispDc.ContainsKey(obj.EventID)) return;
                dispList.Add(obj);
                dispDc.Add(obj.EventID, obj);
            }
            player.Play();
        }

        public void ReportSign(AndonDispWrapper obj) {
            lock (syncObj)
            {
                if (!dispDc.ContainsKey(obj.EventID)) return;
                var wrapper = dispDc[obj.EventID];
                wrapper.SignUserName = obj.SignUserName;
                wrapper.RspTime = obj.RspTime;
            }
        }

        public void ReportClear(AndonDispWrapper obj)
        {
            lock (syncObj)
            {
                if (!dispDc.ContainsKey(obj.EventID)) return;
                var wrapper = dispDc[obj.EventID];
                dispList.Remove(wrapper);
                dispDc.Remove(obj.EventID);
                if (dispList.Count == 0) {
                    this.Close();
                }
            }
        }

        public void SetReduceTime() {
            lock (syncObj)
            {
                foreach (var obj in dispList) {
                    ++obj.ReduceMin;
                }
            }
        }

        void DoGetData() {
            Thread.Sleep(3000);
            IList<AndonDispWrapper> wrapperSet = new List<AndonDispWrapper>();
            while (true) {
                try
                {
                    IList<AndonDispWrapper> set = null; 
                    lock (syncObj) {
                        set = dispList.Select(p => p).ToList();
                    }

                    if (set.Count == 0)
                    {
                        this.Invoke(actSetGridDataSource, wrapperSet);
                        Thread.Sleep(10000);
                        continue;
                    }

                    set = set.OrderByDescending(p => p.StartTime).ToArray();


                    //判断
                    int pageCount = set.Count / page_size;
                    if (set.Count % page_size != 0)
                    {
                        ++pageCount;
                    }

                    for (int idx = 0; idx < pageCount; idx++)
                    {
                        var pagedSet = set.Skip(page_size * idx).Take(page_size).ToList();
                        DateTime curTime = DateTime.Now;
                        pagedSet.ForEach(p =>
                        {
                            double totalTime = curTime.Subtract(p.StartTime).TotalMinutes - p.ReduceMin;
                            p.TotalTime = totalTime < 0 ? 0 : Math.Round(totalTime, 2);
                        });
                        this.Invoke(actSetGridDataSource, pagedSet);
                        Thread.Sleep(20000);
                    }
                }
                catch(Exception ex) {
                    //this.BeginInvoke(actPopErrorMsgForm, ErrorForm, ex.ToString());
                    Thread.Sleep(20000);
                }
            }
        }

        private void lbVersion_DoubleClick(object sender, EventArgs e)
        {
            if (++clickCount >= 5) {
                clickCount = 0;
                this.Close();
            }
        }

        private void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            //var wrapper = gridView2.GetRow(e.RowHandle) as AndonDispWrapper;
            //if(wrapper == null)return;
            //if (string.IsNullOrEmpty(wrapper.SignUserName))
            //{
            //    e.Appearance.BackColor = Color.Crimson;
            //}
        }

        private void gridView2_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right) {
                if (Program.cursorShown)
                {
                    Cursor.Hide();
                }
                else {
                    Cursor.Show();
                }
                Program.cursorShown = !Program.cursorShown;
            }
        }

        private void picLogo_DoubleClick(object sender, EventArgs e)
        {
            if (++restartClickCount >= 5)
            {
                restartClickCount = 0;
                if (_MsgBox.PopQuestion("是否重启看板控制器？") != DialogResult.Yes)
                {
                    return;
                }
                
                System.Diagnostics.Process.Start("Shutdown.exe", @" -r -t 0");
            }
        }

        private void lbTime_DoubleClick(object sender, EventArgs e)
        {
            //using (var frm = new frmConfig()) {
            //    frm.ShowDialog();
            //}
        }

        private void frmAndon_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                dispTh.Abort();
            }
            catch { }
        }
        
    }
}
